import { createResolvablePromise } from '@/utils/common'
import { showToast } from '@/utils/toast'
import {
  Button,
  Modal,
  ModalBody,
  ModalContent,
  ModalFooter,
  ModalHeader,
  useDisclosure,
} from '@heroui/react'
import { forwardRef, useImperativeHandle, useRef } from 'react'
import '../scss/SettingModal.scss'
import { gameStore } from '@/store/gameStore'
// import { invoke } from '@tauri-apps/api/core'
interface Props {}
interface showParams {}

type ResolveType = {}

const title = '设置'

const SettingModal = (_props: Props, ref: any) => {
  const { isOpen, onOpen, onClose } = useDisclosure()
  const successResolve =
    useRef<(value: ResolveType | PromiseLike<ResolveType>) => void>(null)
  useImperativeHandle(ref, () => ({
    show: (_params: showParams) => {
      const [p, resolve] = createResolvablePromise<ResolveType>()
      successResolve.current = resolve

      // TODO: 根据参数渲染

      onOpen()
      return p
    },
  }))

  const onSubmit = () => {
    const data: ResolveType = {}

    successResolve.current(data)
    onClose()
    showToast('添加成功')
  }
  const importInputRef = useRef(null)

  return (
    <Modal isOpen={isOpen} onClose={onClose} className="dark" size="xl">
      <ModalContent>
        {(onClose) => {
          return (
            <>
              <ModalHeader>{title}</ModalHeader>
              <ModalBody className="SettingModal">
                <div className="label">
                  <span>数据管理：</span>
                  <input
                    style={{
                      display: 'none',
                    }}
                    type="file"
                    accept=".json"
                    ref={importInputRef}
                    onChange={(e) => {
                      const file = e.target.files[0]
                      if (!file) return
                      const reader = new FileReader()
                      reader.onload = (e) => {
                        const result = e.target.result
                        const data = JSON.parse(result as string)
                        if (!Array.isArray(data.games)) {
                          showToast('导入失败，数据格式错误')
                          return
                        }
                        gameStore.set(data)
                        showToast('导入成功')
                      }
                      reader.readAsText(file)
                    }}
                  />
                  <Button
                    size="sm"
                    className="btn"
                    color="primary"
                    onPress={() => importInputRef.current.click()}>
                    导入
                  </Button>
                  <Button
                    size="sm"
                    className="btn"
                    color="primary"
                    onPress={async () => {
                      const data = gameStore.value
                      const json = JSON.stringify(data, null, 2)
                      const blob = new Blob([json], {
                        type: 'application/json',
                      })
                      const url = URL.createObjectURL(blob)
                      const a = document.createElement('a')
                      a.href = url
                      a.download = 'gameLauncherDataBackup.json'
                      a.click()
                    }}>
                    导出
                  </Button>
                </div>
              </ModalBody>
              <ModalFooter>
                <Button
                  size="sm"
                  onPress={() => {
                    onClose()
                  }}>
                  取消
                </Button>
                <Button
                  size="sm"
                  color="primary"
                  style={{
                    color: 'white',
                  }}
                  onPress={() => {
                    onSubmit()
                  }}>
                  确定
                </Button>
              </ModalFooter>
            </>
          )
        }}
      </ModalContent>
    </Modal>
  )
}

export default forwardRef(SettingModal)
